﻿using System.Collections.Generic;
using System.Linq;
using PersonaLibrary.Data;

namespace PersonaLibrary.ViewModel.PrintViewModel
{
// ReSharper disable InconsistentNaming
	internal class ContactsConflictVM : PrintChildVM<View.PrintView.ContactsConflict>
// ReSharper restore InconsistentNaming
	{
		
		private List<KeyValuePair<string,string>> _addreses;
		private List<KeyValuePair<string, string>> _phones;
		private KeyValuePair<string, string> _selectedAddress;
		private KeyValuePair<string, string> _selectedPhone;
		private readonly LinqToDbDataContext _context;
		private Employee _selectedEmployee;

		public ContactsConflictVM()
		{
			_context = new LinqToDbDataContext();
		}

		public LinqToDbDataContext Context
		{
			get { return _context; }
		}

		public List<Employee> AllConflictEmployee { set; get; }

		public Employee SelectedEmployee
		{
			set
			{
				_selectedEmployee = value; 
				RisePropertyChanged("SelectedEmployee");
				Addreses = value.GetAllAvailableAddress().ToList();
				Phones = value.GetAllAvailablePhones().ToList();
				if (!string.IsNullOrEmpty(value.DefaultAddress))
					SelectedAddres = Addreses.FirstOrDefault(x => x.Value == _selectedEmployee.DefaultAddress);
				if (!string.IsNullOrEmpty(value.DefaultPhone))
					SelectedPhone = Phones.FirstOrDefault(x => x.Value == _selectedEmployee.DefaultPhone);
				RisePropertyChanged("SelectedConnection");
			}
			get { return _selectedEmployee; }
		}

		public List<KeyValuePair<string, string>> Addreses
		{
			set
			{
				_addreses = value;
				RisePropertyChanged("Addreses");
			}
			get { return _addreses; }
		}

		public List<KeyValuePair<string, string>> Phones
		{
			set
			{
				_phones = value;
				RisePropertyChanged("Phones");
			}
			get { return _phones; }
		}

		public KeyValuePair<string, string> SelectedAddres
		{
			set 
			{ 
				_selectedAddress = value;
				RisePropertyChanged("SelectedAddres");
				SelectedEmployee.DefaultAddress = value.Value;
			}
			get { return _selectedAddress; }
		}

		public KeyValuePair<string, string> SelectedPhone
		{
			set
			{
				_selectedPhone = value;
				RisePropertyChanged("SelectedPhone");
				SelectedEmployee.DefaultPhone = value.Value;
			}
			get { return _selectedPhone; }
		}
		
		public ConnectionJobEmplDep SelectedConnection
		{
			set 
			{
				RisePropertyChanged("SelectedConnection");
				if(value != null)
					SelectedEmployee.DefaultOrganization = value.Department.Organization.ToString();
			}
			get
			{
				if(SelectedEmployee != null)
					return SelectedEmployee.ConnectionJobEmplDeps.FirstOrDefault(x => x.Department.Organization.ToString() == SelectedEmployee.DefaultOrganization);
				return null;
			}
		}

		public override void Dispose()
		{
			_context.SubmitChanges(false);
			_context.Dispose();
			base.Dispose();
		}
	}
}
